package abel.wlmr.model.unit;

import java.util.ArrayList;
import java.util.List;

import abel.wlmr.model.WlmrBasePart;
import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrDefaultUnit;
import abel.wlmr.model.WlmrException;
import abel.wlmr.model.type.DataIdBody;
import io.netty.buffer.ByteBuf;

/**
 * B.5.5.1.3.3 F31： 对时命令
 * 数据单元格式见表 B.51。
 * 表B.51 对时命令数据单元格式
 * 数据内容 数据格式 字节数
 * 秒、分、时、日、星期-月、年 见附录 C.1 6
 * 
 * @author Abel
 *
 */
public abstract class Afn05Part extends WlmrBasePart {
    public static final short F_SYNC = 31;

    public Afn05Part() {
        super();
    }

    public Afn05Part(short guessedLen) {
        super(guessedLen);
    }

    /**
     * Supports 05-F31 only.
     * 
     */
    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        id = new DataIdBody();
        id.parseBuf(buf);

        short restLen = (short) (getGuessedLength() - 4);

        // same DA.
        List<WlmrBaseUnit> units = new ArrayList<>();
        unitList.add(units);

        // DT list for one DA.
        for (short dt : id.getDt().typeList()) {
            DataIdBody outerId = new DataIdBody();
            outerId.getDa().setAddrList(new short[0]);
            outerId.getDt().setTypeList((short) 31);

            switch (dt) {
            case 31:

            {
                Afn05F31Unit unit = new Afn05F31Unit(restLen);
                unit.setOuterId(outerId);

                int plen = unit.parseBuf(buf);
                if (plen < 0) {
                    throw new WlmrException("fail to parse 05-F31 unit");
                }

                restLen -= plen;
                units.add(unit);

                break;
            }
            default:

            {
                WlmrBaseUnit unit = new WlmrDefaultUnit(restLen);
                unit.setOuterId(id);

                restLen -= unit.parseBuf(buf);
                units.add(unit);

                break;
            }
            }
        }

        buf.skipBytes(restLen);
        return getGuessedLength();
    }

}
